package nancal.mp.mvc.sys

import com.warrenstrange.googleauth.GoogleAuthenticatorKey
import nancal.mp.db.mongo.mor
import nancal.mp.service.GoogleAuthenticatorService
import nbcp.base.annotation.mvc.OpenAction
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.db.LoginUserModel
import nbcp.base.extend.must
import nbcp.myoql.db.mongo.updateById
import org.springframework.web.bind.annotation.*
import java.util.*

@RestController
@RequestMapping("/api/auth")
internal class AuthController(val googleAuthenticatorService: GoogleAuthenticatorService) {

    @PostMapping("/secret-key")
    fun generateSecretKey(loginUser: LoginUserModel): JsonResult {
        val key = googleAuthenticatorService.createSecretKey(loginUser.loginName)
        mor.admin.adminLoginUser.updateById(loginUser.id)
            .set { it.totpKey to key.key }
            .exec()
        return JsonResult();
    }

    @PostMapping("/close")
    fun closeSecretKey(loginUser: LoginUserModel): JsonResult {
        mor.admin.adminLoginUser.updateById(loginUser.id)
            .set { it.totpKey to "" }
            .exec()
        return JsonResult();
    }


    class QrCodeData(
        var img: String = "",
        var key: String = ""
    )

    @GetMapping("/qr-code")
    @Throws(Exception::class)
    fun generateQRCode(loginUser: LoginUserModel): ApiResult<QrCodeData> {
        var adminLoginUser = mor.admin.adminLoginUser.queryById(loginUser.id).toEntity()
            .must()
            .elseThrow { "找不到用户" }

        if (adminLoginUser.totpKey.isEmpty()) {
            return ApiResult.error("未开启身份验证器");
        }
        val qrCodeUrl: String =
            googleAuthenticatorService.getQRCodeUrl(adminLoginUser.totpKey, adminLoginUser.loginName, "开发平台")

        return ApiResult.of(QrCodeData(qrCodeUrl, adminLoginUser.totpKey));
    }


    @PostMapping("/verify/{code}")
    fun verifyCode(loginUser: LoginUserModel, @PathVariable code: Int): ApiResult<Boolean> {
        var adminLoginUser = mor.admin.adminLoginUser.queryById(loginUser.id).toEntity()
            .must()
            .elseThrow { "找不到用户" }

        var ret = googleAuthenticatorService.authorize(adminLoginUser.totpKey, code)
        return ApiResult.of(ret)
    }
}


